package com.it.security.service;

import com.it.security.pojo.Permission;
import com.it.security.pojo.Role;
import com.it.security.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    HttpServletRequest request;

    @Autowired
    UserService userService;

    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RoleService roleService;

    @Autowired
    PermissionService permissionService;
    
    @Autowired
    RolerPermissionService rolerPermissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        log.info(user.getUsername());
        if (user == null){
            throw new UsernameNotFoundException("用户名不存在!");
        }
        log.info("调用MyUserDetailsService 用户名："+username);
        HttpSession session = request.getSession();
        session.setAttribute("user",username);
        session.setAttribute("sessusername",username);

        List<GrantedAuthority> authoritiess = getAuthorityByUser(username);

        //List<GrantedAuthority> authorities = new ArrayList<>();

        //角色
        //authorities.add(new SimpleGrantedAuthority(user.getRole()));
        //authorities.add(new SimpleGrantedAuthority("1"));

        //权限（为了测试，硬编码，实际上应该从数据库中读取）
        //authorities.add(new SimpleGrantedAuthority("1"));

        //logger.info(user.getName()+"角色权限为："+authorities.toString());


//        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//        String password = passwordEncoder.encode("123456");


        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authoritiess);
    }

    /**
     * 根据用户名查询出 当前用户的角色 和 权限 返回一个权限列表
     * @param username
     * @return
     */
    public List<GrantedAuthority> getAuthorityByUser(String username){
        // 存放角色 和权限的列表
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 根据用户名称 查询出当前用户的角色
        User user = userService.findByUsername(username);
        // 根据用户id去 user_role表中查询出角色id
        List<Integer> roles = userRoleService.getRoleByUserId(user.getId());
        // 遍历角色id列表
        for(Integer roleId:roles){
            // 根据id查询查询ole
            Role role = roleService.getRoleById(roleId);
            // 添加 角色关键字到 权限列表当中
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));

            // 根据角色id 到角色与权限关联表中 查询出权限id
            List<Integer> permissionIds = rolerPermissionService.getPermissionByRolerId(role.getId());
            // 遍历权限id
            for(Integer permissionId:permissionIds){
                // 根据权限id查询出 权限对象
                Permission permission = permissionService.getPermissionById(permissionId);
                // 将权限关键字添加到 权限列表中
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));

            }


        }
        System.out.println("当前用户的权限列表："+authorities);

        // 根据角色查询出 当前角色有哪些权限
        return authorities;




    }


}
